package com.study.controller;

import com.study.entity.PageBean;
import com.study.entity.Result;
import com.study.entity.Student;
import com.study.entity.StudentQueryParam;
import com.study.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/students")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping
    public Result list(StudentQueryParam param) {
        PageBean pageBean = studentService.list(param);
        return Result.success(pageBean);
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable String ids) {
        String[] sArr = ids.split(",");
        for (String s : sArr) {
            Integer id = Integer.valueOf(s);
            log.info("id={}", id);
            studentService.delete(id);
        }
        return Result.success();
    }

    @PostMapping
    public Result add(@RequestBody Student student) {
        studentService.add(student);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getByid(@PathVariable Integer id) {
        Student student = studentService.getByid(id);
        return Result.success(student);
    }

    @PutMapping
    public Result update(@RequestBody Student student) {
        studentService.update(student);
        return Result.success();
    }
    @Transactional
    @PutMapping("/violation/{id}/{score}")
    public  Result violate(@PathVariable Integer id,@PathVariable Integer score){
        Student student = studentService.getByid(id);
        student.setUpdateTime(LocalDateTime.now());
        Short violationCount = student.getViolationCount();
        student.setViolationCount((short)(violationCount+1));
        Short violationScore = student.getViolationScore();
        student.setViolationScore((short)(violationScore+score));
        studentService.update(student);
        return Result.success();
    }
}
